#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <string>

class EventQueue {
    public:
    using EventHandler = std::function<void (const std::string&)>;

    void addListener(EventHandler handler) {
        std::lock_guard<std::mutex> lock(mutex);
    }

    void postEvent(const std::string& event) {
        std::lock_guard<std::mutex> lock(mutex);
        std::cout << event << std::endl;
        events.push(event);
        condition.notify_one();
    }

    void run() {
        while (true)
        {
            std::unique_lock<std::mutex> lock(mutex);
            // events不为空时等待，等待事件，确保非空时才尝试取出事件
            std::cout << "1" << std::endl;
            condition.wait(lock, [this]{ return !events.empty();});
            std::cout << "2" << std::endl;

            auto event = events.front();
            events.pop();
            lock.unlock();

            for (auto& handler : handlers) {
                handler(event);
            }

        }
    }

    private:
    std::queue<std::string> events;
    std::vector<EventHandler> handlers;
    std::mutex mutex;
    std::condition_variable condition;
};

int main() {

    EventQueue queue;

    // 添加监听器
    queue.addListener([](const std::string& event){
        std::cout << "Handler 1: " << event << std::endl;
    });

    queue.addListener([](const std::string& event){
        std::cout << "Handler 2: " << event << std::endl;
    });


    // 启动事件处理线程
    std::thread woker([&queue] {queue.run();});

    // 主线程发布事件
    queue.postEvent("Event 1");
    queue.postEvent("Event 2");

    std::this_thread::sleep_for(std::chrono::seconds(3));
    woker.detach();


    return 0;
}